package com.plian.system.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.plian.system.entity.sys.ythtask.YthRetryInfo;
import com.plian.system.entity.sys.ythtask.YthTaskInfo;
import com.plian.system.service.sys.ythtask.IYthRetryInfoService;
import com.plian.system.service.sys.ythtask.IYthTaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class YthTaskObserverAspect {

    @Autowired
    private IYthTaskInfoService ythTaskInfoService;

    @Autowired
    private IYthRetryInfoService ythRetryInfoService;

    @Around("@annotation(com.plian.system.config.YthTaskObserver)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取注解信息
        String serviceName = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        Object[] pointArgs = joinPoint.getArgs();
        //获取第一个参数
        String dataUpdateTime  = (String)pointArgs[0];
        YthTaskInfo ythTaskInfo = new YthTaskInfo();
        ythTaskInfo.setServiceName(serviceName);
        ythTaskInfo.setMethodName(methodName);
        ythTaskInfo.setExecutionTime(new Date());
        ythTaskInfo.setDataUpdateTime(dataUpdateTime);

        YthRetryInfo ythRetryInfo = new YthRetryInfo();
        ythRetryInfo.setServiceName(serviceName);
        ythRetryInfo.setMethodName(methodName);
        ythRetryInfo.setDataUpdateTime(dataUpdateTime);
        Object result = null;
        try {
            result = joinPoint.proceed();
            if (result instanceof Boolean){
                Boolean taskStatus = (Boolean) result;
                ythTaskInfo.setTaskStatus(taskStatus ? 1 : 2);
                if (!taskStatus){
                    ythTaskInfo.setFailureReason("执行失败");
                    ythRetryInfoService.save(ythRetryInfo);
                }
            }
        }catch (Exception e) {
            ythTaskInfo.setTaskStatus(2);
            ythTaskInfo.setFailureReason(ExceptionUtil.getMessage(e));
            ythRetryInfoService.save(ythRetryInfo);
            log.error("一体化平台数据同步失败", e);
        }
        ythTaskInfoService.save(ythTaskInfo);
        return result;
    }
}
